package com.hlx.controller.user;

import com.hlx.entity.admin.Station;
import com.hlx.entity.admin.TrainNumber;
import com.hlx.entity.user.TrainNumberStation;
import com.hlx.service.admin.StationService;
import com.hlx.service.admin.TrainNumberService;
import com.hlx.service.user.TrainNumberStationService;
import com.hlx.utils.Result;
import com.hlx.vo.StationVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/stationVo")
public class StationVoController {
    @Autowired
    private StationService stationService;
    @Autowired
    private TrainNumberService trainNumberService;
    @Autowired
    private TrainNumberStationService trainNumberStationService;

    @PostMapping("/getAllTrain/{stationName}")
    public Result<List<StationVo>> getAllTrain(@PathVariable("stationName") String stationName){
        log.info(stationName);
        Station st = stationService.getStationByName(stationName);
        if(st == null){
            return Result.error("查无此车站");
        }
        List<TrainNumberStation> tns = trainNumberStationService.getTrainNumberStationByStationName(stationName);
        if(tns.isEmpty()){
            return Result.error("无车次");
        }
        List<String> trainNum = tns.stream().map(item->item.getTrainNumberName()).collect(Collectors.toList());
        List<TrainNumber> tn = trainNumberService.getTrainNumberByName(trainNum);
        if(tn.isEmpty()){
            return Result.error("系统错误");
        }
        List<StationVo> sv = new ArrayList<>();
        Iterator<TrainNumber> it = tn.iterator();
        Iterator<TrainNumberStation> its= tns.iterator();
        LocalDate date = LocalDate.now();
        while(it.hasNext()){
//            its.hasNext();
            TrainNumber train = it.next();
            TrainNumberStation trainS = its.next();
            if(!trainNumberService.exitTrainData(train.getTrainNumberName(),date)){
                continue;
            }
            StationVo svo = new StationVo();
            svo.setTrainNumber(train.getTrainNumberName());
            svo.setStationStart(train.getStationStart());
            svo.setStationEnd(train.getStationEnd());
            svo.setArriveTime(trainS.getArriveTime());
            svo.setStartTime(trainS.getStartTime());
            svo.setStationName(st.getStationName());
            svo.setStationAddress(st.getStationAddress());
            sv.add(svo);
        }
        sv.sort((item1,item2) -> item1.getArriveTime().compareTo(item2.getArriveTime()));
        System.out.println(sv);
        if(sv.isEmpty()){
            return Result.error("无车次");
        }
        return Result.success(sv);
    }
}
